<!-- 自动抄表修正 -->
<template>
  <div class="flex-center table-top">
    <px-form ref="formRef" :model="queryParams" :inline="true" class="custom-form-ui search-form">
      <px-form-item label="化学品" prop="chemical">
        <px-select
          v-model="queryParams.chemical"
          style="width: 260px"
          clearable
          filterable
          remote
          reserve-keyword
          remote-show-suffix
          :remote-method="remoteMethod"
          :loading="chemicalLoading"
          placeholder="请输入化学品"
        >
          <px-option v-for="item in chemicalOptions" :key="item" :label="item" :value="item" />
        </px-select>
      </px-form-item>
      <px-form-item label="日期" prop="date">
        <px-date-picker v-model="queryParams.date" type="date" placeholder="请选择日期" value-format="YYYY-MM-DD" style="width: 260px" />
      </px-form-item>
      <div class="search-form-btn">
        <px-button type="primary" @click="handleQuery">查询</px-button>
        <px-button @click="resetQuery">重置</px-button>
        <!-- <px-button v-has="`GAS_CONSUMPTION_CHEMICAL_METER_INSPECTION_BTN`" type="primary" :disabled="spotCheckDisabled" @click="spotCheckClick"
          >点检</px-button
        >
        <px-button v-has="`GAS_CONSUMPTION_CHEMICAL_METER_HISTORY_BTN`" type="primary" @click="spotCheckClickHistory">点检历史</px-button> -->
        <px-button v-has="`GAS_CONSUMPTION_CHEMICAL_METER_EXPORT_BTN`" @click="handleExport">导出</px-button>
      </div>
    </px-form>
  </div>
  <div ref="tableBoxRef" v-loading="tableLoading" class="table-content">
    <px-table :data="tableData" :span-method="objectSpanMethod" size="small" border class="common-table" :height="scrollbarHeight">
      <!-- <px-table-column type="index" label="序号" fixed width="55" align="center" /> -->
      <px-table-column prop="gasChemicalName" label="化学品" min-width="120" fixed show-overflow-tooltip />
      <px-table-column prop="unit" label="单位" min-width="80" fixed show-overflow-tooltip />
      <px-table-column prop="itemName" label="抄表项目" min-width="120" show-overflow-tooltip />
      <px-table-column label="实时余量" fixed min-width="120" show-overflow-tooltip>
        <template #default="scope">
          <div class="progress-wrap">
            <px-progress
              status="success"
              size="small"
              :stroke-width="15"
              :text-inside="true"
              :percentage="scope.row.showPercentage"
              :format="() => progressFormat(scope.row)"
            />
            <span class="text">{{ scope.row.currentValue }}</span>
          </div>
        </template>
      </px-table-column>
      <px-table-column label="抄表值" min-width="120" header-align="center">
        <px-table-column v-for="i in dayData" :key="i" :prop="i" :label="i" />
      </px-table-column>
      <px-table-column label="操作" width="100" fixed="right" align="center">
        <template #default="scope">
          <px-tooltip content="编辑" placement="top">
            <px-button v-has="`GAS_CONSUMPTION_CHEMICAL_METER_EDIT_BTN`" link icon="EditPen" type="primary" @click="handleEdit(scope.row)" />
          </px-tooltip>
        </template>
      </px-table-column>
    </px-table>
  </div>

  <px-dialog v-model="editDialogVisible" title="编辑" width="400">
    <px-form ref="editFormRef" :model="editFormParams">
      <px-form-item label="当日抄表值" prop="readValue">
        <px-input v-model.trim="editFormParams.readValue" placeholder="请输入" clearable />
      </px-form-item>
    </px-form>
    <template #footer>
      <span class="dialog-footer">
        <px-button @click="cancelEdit">取消</px-button>
        <px-button type="primary" @click="saveEdit">确定</px-button>
      </span>
    </template>
  </px-dialog>

  <!-- 点检弹框  -->
  <div v-if="spotCheckDialogVisible">
    <SpotCheckDialog v-model:visible="spotCheckDialogVisible" :tableData="spotCheckHistorykData" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, toRefs, onMounted, onUnmounted, getCurrentInstance } from "vue";
import { getMeterReadingListAPI, editMeterReadingListAPI } from "@/api/consumption/chemical";
import { queryAllChemicalName } from "@/api/modules/operation";
import { PxMessage } from "px-ui";
import SpotCheckDialog from "../../component/spotCheckDialog.vue";
import { useSpotCheckHook, useExportHook } from "../../hook.js";
import { useUpdateDomHeight, useCancelUpdateDomHeight } from "@/hooks/useCommon";

defineOptions({
  name: "GAS_CONSUMPTION_CHEMICAL_METERREADING"
});

const formRef = ref(null);
const editFormRef = ref(null);
const { proxy } = getCurrentInstance();

const gap = 40;
const defaultHeight = 606;
const scrollbarHeight = ref<number>(defaultHeight);
const tableBoxRef = ref<HTMLElement | null>(null);
const chemicalLoading = ref<boolean>(false);
const chemicalOptions = ref<Array<any>>([]);

const state = reactive({
  queryParams: {
    chemical: "",
    date: ""
  },
  tableLoading: false,
  tableData: [],
  dayData: [],
  editFormParams: {
    coefficient: null
  },
  editDialogVisible: false,
  editRowData: {}
});
const { queryParams, tableLoading, tableData, dayData, editFormParams, editDialogVisible, editRowData } = toRefs(state);

const remoteMethod = async (searchKey: string) => {
  if (searchKey) {
    chemicalLoading.value = true;
    const res = await queryAllChemicalName({ searchKey }, () => {
      chemicalLoading.value = false;
    });
    chemicalOptions.value = res;
    chemicalLoading.value = false;
  } else {
    chemicalOptions.value = [];
  }
};

onMounted(async () => {
  handleQuery();
  await useUpdateDomHeight(scrollbarHeight, tableBoxRef, gap, defaultHeight);
});

onUnmounted(() => useCancelUpdateDomHeight());

const { spotCheckHistorykData, spotCheckDialogVisible, spotCheckDisabled, spotCheckClick, spotCheckClickHistory } = useSpotCheckHook("CHEMICAL");
const params = {
  itemKey: state.queryParams.chemical,
  searchDate: state.queryParams.date
};
const { handleExport } = useExportHook(proxy, "CHEMICAL_METERREADING", params);

const spanArr = ref([]);
const position = ref(0);
// 查询
const handleQuery = async () => {
  try {
    state.tableLoading = true;
    const { chemical, date } = state.queryParams;
    const params = {
      itemKey: chemical,
      searchDate: date
    };
    const res = await getMeterReadingListAPI(params);
    if (res?.length) {
      // 把上次的表格的合并行，进行重置
      spanArr.value = [];
      position.value = 0;
      res.forEach((i, index) => {
        let dayValues = i.dayValues;
        // 把日期提取最外层，日期：值，
        dayValues.forEach(j => {
          let planTime = j?.planTime?.split(" ")[0] || "";
          let readValue = j?.readValue !== null ? j?.readValue : "-";
          i[planTime] = readValue;
        });
        // 把抄表值的最后一个日期拿出来
        i.planTime = dayValues?.[dayValues?.length - 1]?.planTime;
        // 从第一个元素中提取日期组成数组
        if (index === 0) {
          let arr = [];
          dayValues.forEach(k => {
            let planTime = k?.planTime?.split(" ")[0] || "";
            arr.push(planTime);
          });
          state.dayData = [...new Set(arr)];
        }
        // 计算实时余量
        let num = 0;
        if (i.currentValue && i.fullValue) {
          const quotient = i.currentValue / i.fullValue;
          num = Math.round(quotient * 100);
        }
        // 显示的量
        i.showPercentage = num >= 100 ? 100 : num;
        // 实际的实时余量
        i.actualValue = num;
        // 计算合并行
        if (index === 0) {
          spanArr.value.push(1);
          position.value = 0;
        } else {
          if (i.gasChemicalName === res[index - 1].gasChemicalName) {
            spanArr.value[position.value]++;
            spanArr.value.push(0);
          } else {
            spanArr.value.push(1);
            position.value = index;
          }
        }
      });
      state.tableData = res;
    } else {
      state.tableData = [];
    }
  } catch (err) {
    console.log(err);
  } finally {
    state.tableLoading = false;
  }
};
// 自定义合并行的方法
const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  if (columnIndex === 0) {
    const rowspan = spanArr.value[rowIndex];
    if (rowspan > 0) {
      return {
        rowspan: rowspan,
        colspan: 1
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0
      };
    }
  }
};
// 文本过滤显示
const progressFormat = row => {
  let actualValue = row?.actualValue;
  return `${actualValue}%`;
};
// 重置
const resetQuery = () => {
  formRef.value.resetFields();
  handleQuery();
};

// 编辑
const handleEdit = row => {
  state.editRowData = row;
  state.editFormParams = {
    readValue: row.readValue
  };
  state.editDialogVisible = true;
};

// 取消编辑
const cancelEdit = () => {
  editFormRef.value.resetFields();
  state.editDialogVisible = false;
};

// 保存编辑
const saveEdit = async () => {
  const { id, gasChemicalName, planTime } = state.editRowData;
  const params = {
    id,
    itemKey: gasChemicalName,
    planTime,
    pointValue: state.editFormParams.readValue
  };
  await editMeterReadingListAPI(params);
  PxMessage.success("修改成功");
  cancelEdit();
  handleQuery();
};
</script>

<style lang="scss" scoped>
@import url("@/views/gas/consumption/scss/common.scss");
</style>
